package org.example.shoppingmall.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisUtil {
    private static JedisPool pool = null;

    // Redis服务器地址
    private static final String REDIS_HOST = "localhost";
    // Redis端口号
    private static final int REDIS_PORT = 6379;
    // Redis密码（如果没有密码，设为null或空字符串）
    private static final String REDIS_PASSWORD = ""; // 替换为你的Redis密码

    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(128);
            config.setMaxIdle(128);
            config.setMinIdle(16);
            config.setTestOnBorrow(true);
            config.setTestOnReturn(true);
            config.setTestWhileIdle(true);
            config.setMinEvictableIdleTimeMillis(60000);
            config.setTimeBetweenEvictionRunsMillis(30000);
            config.setNumTestsPerEvictionRun(-1);

            // 创建Jedis连接池，配置为本地的Redis服务器
            if (REDIS_PASSWORD != null && !REDIS_PASSWORD.isEmpty()) {
                pool = new JedisPool(config, REDIS_HOST, REDIS_PORT, 2000, REDIS_PASSWORD);
            } else {
                pool = new JedisPool(config, REDIS_HOST, REDIS_PORT, 2000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Jedis getJedis() {
        return pool.getResource();
    }

    public static void release(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    public static void set(String key, String value, int expiry) {
        try (Jedis jedis = getJedis()) {
            jedis.setex(key, expiry, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String get(String key) {
        try (Jedis jedis = getJedis()) {
            return jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void delete(String key) {
        try (Jedis jedis = getJedis()) {
            jedis.del(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
